<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring" %>
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Главная </title>
<meta http-equiv='Content-Type' content='text/html; charset=UTF-8'/>

<link rel="stylesheet" type="text/css" href="/css/template.css"/>
<link rel="stylesheet" type="text/css" href="/css/gallery.css"/>
<link rel="stylesheet" type="text/css" href="/css/dark.css"/>
<link rel="stylesheet" type="text/css" href="/css/buttons.css"/>
<link href='http://fonts.googleapis.com/css?family=Lobster&subset=latin,cyrillic' rel='stylesheet' type='text/css'>
<link rel="stylesheet" type="text/css" href="/css/data_table/jquery.dataTables.css"/>
<link rel="stylesheet" type="text/css" href="/css/data_table/jquery.dataTables_themeroller.css"/>
<link rel="stylesheet" type="text/css" href="/css/basic/basic.css"/>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet"
      type="text/css"/>
<link rel="stylesheet" type="text/css" href="/css/dark.css"/>
<link rel="stylesheet" type="text/css" href="/css/add_lantern.css"/>


<script type="text/javascript" src="/js/jquery-1.8.2.js"></script>
<script type="text/javascript" src="/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="/js/jquery.lavalamp.min.js"></script>
<script type="text/javascript" src="/js/cufon.yui.js"></script>
<script type="text/javascript" src="/js/myriad.js"></script>
<script type="text/javascript" src="/js/menu.js"></script>
<script type="text/javascript" src="/js/data_table/jquery.dataTables.js"></script>
<script type="text/javascript" src="/js/basic/jquery.simplemodal.js"></script>
<script type="text/javascript" src="/js/menu.js"></script>
<script type="text/javascript" src="/js/jquery.easing.min.js"></script>
<script type="text/javascript" src="/js/jquery.easing.compatibility.js"></script>
<script type="text/javascript" src="/js/ckeditor/ckeditor.js"></script>
<script type="text/javascript" src="/js/ckeditor/adapters/jquery.js"></script>
<script type="text/javascript" src="/js/ajax/ajaxupload.3.5.js"></script>
<script type="text/javascript" src="/js/jquery.validate.js"></script>

<script type="text/javascript" src="/js/rules.js"></script>
<script type="text/javascript" src="/js/about.js"></script>
<script type="text/javascript" src="/js/news.js"></script>
<script type="text/javascript" src="/js/contacts.js"></script>

<script type="text/javascript">

function resetTabs() {
    $("#cont div").hide(); //Скрываем содержание
    $("#eight a").attr("id", ""); //Сбрасываем id
}


function tabs() {
    var myUrl = window.location.href; //Получаем URL
    var myUrlTab = myUrl.substring(myUrl.indexOf("#")); // Для localhost/tabs.html#tab2 myUrlTab = #tab2
    myUrlTab = "#tab1";
    var myUrlTabName = myUrlTab.substring(0, 4); // Для выше привденного примера myUrlTabName = #tab

    $("#cont div").hide(); // Скрываем все содержание при инициализации
    $("#eight li:first a").attr("id", "current"); // Активируем первую закладку
    $('#cont div:first').fadeIn();
    //$('#cont div:first *').fadeIn();

    $("#eight a").on("click", function (e) {
        e.preventDefault();
        if ($(this).attr("id") == "current") { //Определение текущейй закладки
            return
        }
        else {
            resetTabs();
            $(this).attr("id", "current"); // Активируем текущую закладку
            $($(this).attr('name')).fadeIn();
            $($(this).attr('name') + ' div').fadeIn();

        }
    });

    for (i = 1; i <= $("#eight li").length; i++) {
        if (myUrlTab == myUrlTabName + i) {
            resetTabs();
            $("a[name='" + myUrlTab + "']").attr("id", "current"); // Активируем закладку по url
            $(myUrlTab).fadeIn();
            $(myUrlTab + ' div').fadeIn();
        }
    }
}

function removeUser(id) {
    $.ajax({
        type:"POST",
        url:"/admin/delete_user.html",
        data:{user_id:id},
        success:function () {
            var $tr = $('#user_' + id);
            $tr.remove();
            $('#users').dataTable();
        }

    });
}

function viewUserOrder(id) {
    if ($("#order_" + id).css('display') == 'none') {
        $("#order_" + id).fadeIn();

    } else {
        $("#order_" + id).fadeOut();
    }
}

$('document').ready(function () {
    var config = {
        skin:'v2'
    };
    // Initialize the editor.
    // Callback function can be passed and executed after full instance creation.
    $('.jquery_ckeditor').ckeditor(config);

    loadAction();

    $('#lanters').dataTable();
    $("#users").dataTable();
    $("#order").dataTable();

    tabs();

    $("#submit_action").bind("click", function () {
        saveAction();
    });

    $("#submit_rules").bind("click", function () {
        addContentPage('rules', '1');
    });
    $("#submit_news").bind("click", function () {
        addContentPage('news', '3');
    });
    $("#submit_about").bind("click", function () {
        addContentPage('about', '4');
    });
    $("#submit_contacts").bind("click", function () {
        addContentPage('contacts', '2');
    });

    getContentPage('rules', '1');
    getContentPage('contacts', '2');
    getContentPage('news', '3');
    getContentPage('about', '4');


    actionLoadImage();
    rulesImageLoader();
    contactsImageLoader();
    aboutImageLoader();
    newsImageLoader();

    var addrules = {
        rules:{
            description:{
                required:true
            },

            price:{
                digits:true,
                required:true
            },
            lanter_cat:{
                required:true
            }
        },
        messages:{
            lanter_cat:{
                required:"обязательное"
            },

            description:{
                required:"обязательное"
            },

            price:{
                digits:"введите число",
                required:"обязательное"
            }
        }
    }

    var rules = {
        rules:{
            description:{
                required:true
            },
            document_file:{
                required:true
            },
            price:{
                digits:true,
                required:true
            },
            lanter_cat:{
                required:true
            }
        },
        messages:{
            lanter_cat:{
                required:"обязательное"
            },

            description:{
                required:"обязательное"
            },
            document_file:{
                required:"обязательное"
            },
            price:{
                digits:"введите число",
                required:"обязательное"
            }
        }
    }

    $("#add_form").validate(rules);
    $("#lantern_form").validate(addrules);

});

function deleteLantern(id) {
    $.ajax({
        type:"POST",
        url:"/admin/removelantern.html",
        data:{lantern_id:id},
        success:function (json) {
            var $tr = $('#lanter_' + id);
            $tr.remove();
            $('#lanters').dataTable();
        }
    });

}

function updateLantern(id) {
    $.ajax({
        type:"POST",
        url:"/admin/getlantern.html",
        data:{lantern_id:id},
        success:function (json) {
            $('#basic-modal-content').modal();
            $.each(json, function (key, value) {
                if (key == 'description') {
                    $('#description').val(value);
                } else if (key == 'price') {
                    $('#price').val(value);
                } else if (key == 'category') {
                    $('#cat').val(value["idCategory"]);
                } else if (key == 'idLantern') {
                    $('#lantern_form').append('<input type="hidden" name="id" value=' + value + '>');
                }
            });
        }
    });
}

function loadAction() {
    $.ajax({
        type:"POST",
        url:"/admin/get_action.html",
        success:function (json) {
            $.each(json, function (key, value) {
                if (key == 'description') {
                    $("#elm2").val(value);
                }
                if (key == 'idAction' && value != null) {
                    $('#action_form').append('<input id="action_id" type="hidden" name="action_id" value=' + value + '>');
                }
            });
        }
    });
}

function saveAction() {
    $.ajax({
        type:"POST",
        url:"/admin/action_save.html",
        data:{elm2:$("#elm2").val(), is_active:$("is_active").val(), action_id:$("#action_id").val()},
        success:function () {
            alert("Обновлено");
        }
    });
}

var imageArray = [];
var image = {
    imgUrl:null
};
var image_list_length = 1;
function actionLoadImage() {
    var btnUpload = $('#upload');
    var status = $('#status');
    new AjaxUpload(btnUpload, {
        action:'/admin/add_image.html',
        name:'fileUpload',
        onSubmit:function (file, ext) {
            if (!(ext && /^(jpg|png|jpeg|gif)$/.test(ext))) {
                // extension is not allowed
                status.text('Only JPG, PNG or GIF files are allowed');
                return false;
            }
            status.text('Uploading...');
        },
        onComplete:function (file, response) {
            //On completion clear the status
            status.text('');
            //Add uploaded file to list
            var params = response.split(',');
            var name = params[1].split('/');
            var text;
            if (params[0] === "success") {
                $('<li></li>').appendTo('#files').html('<img style="width: 200px; height: 200px" src=' + params[1] + ' alt="" /><br /><p>' + name[3] + '</p>').addClass('success');
                image = {
                    imgUrl:params[1]
                }
                image_list_length++;
                imageArray.push(image);

            } else {
                $('<li></li>').appendTo('#files').text(file).addClass('upload_error');
            }
        }
    });
}

function getContentPage(idContent, id) {
    var $item = $("#" + idContent);
    $.ajax({
        type:"POST",
        url:"/admin/get_content_page.html",
        data:{id:id},
        success:function (json) {
            $.each(json, function (key, value) {
                if (key == 'content') {
                    $item.val(value);
                }
            });
        }
    });


}

function addContentPage(idContent, id) {
    var $item = $("#" + idContent);

    $.ajax({
        type:"POST",
        url:"/admin/upload_page_content.html",
        data:{id:id, content:$item.val()},
        success:function () {
            alert("Успешно");
        }
    });
}

function chechPassword() {
    if ($("#new_pswd").val() == $("#new_r_pswd").val()) {
        $.ajax({
            type:"POST",
            url:"/admin/check_pswd.html",
            data:{pswd:$("#cur_pswd").val()},
            success:function (data) {
                if (data == 'yes') {
                    changePassword();
                } else {
                    alert("Неверный пароль");
                    $("#pswd_message").val("Неверный пароль");
                }
            }
        });
    } else {
        $("#pswd_message").val("Проверьте поля ввода");
        alert("Проверьте поля ввода");
    }


}

//<td><label for="new_pswd">Новый пароль:&nbsp;</label></td>
//        <td><input name="new_pswd" value="" id="new_pswd"/></td>
//
//        </tr>
//
//        <tr>
//        <td><label for="new_r_pswd">Повторите новый пароль:&nbsp;</label></td>
//        <td><input  name="new_r_pswd" id="new_r_pswd"/></td>


function changePassword() {
    $.ajax({
        type:"POST",
        url:"/admin/change_pswd.html",
        data:{pswd:$("#new_pswd").val()},
        success:function () {
            alert("Пароль изменен");
        }
    });
}


</script>


<style type="text/css">

    .container_16 .grid_16 .upload_error {
        background: #f0c6c3;
        border: 1px solid #cc6622;
    }

    .container_16 .grid_16 .image_container {
        width: 960px;
        display: block;
        position: relative;

    }

    .container_16 .grid_16 .image_container ul#files {
        list-style: none;
        padding: 0;
        margin: 0;
    }

    .success {
        position: relative;
    }

    .container_16 .grid_16 .image_container ul#files li {
        padding: 10px;
        margin-bottom: 2px;
        width: 180px;
        float: left;
        margin-right: 15px;
        position: relative;
    }

    .container_16 .grid_16 .image_container ul#files li img {
        max-width: 150px;
        max-height: 150px;
        min-width: 150px;
        min-height: 150px;
    }

    body {
        font-family: Arial, Helvetica, sans-serif;
    }

    #bar {
        background-color: #7dc242;
        width: 0px;
        height: 16px;
    }

    #barbox {
        float: right;
        height: 16px;
        background-color: #FFFFFF;
        width: 100px;
        border: solid 2px #6b6c6e;
        margin-right: 3px;
        -webkit-border-radius: 5px;
        -moz-border-radius: 5px;
    }

    #count {
        float: right;
        margin-right: 8px;
        font-family: 'Georgia', Times New Roman, Times, serif;
        font-size: 16px;
        font-weight: bold;
        color: #666666
    }
</style>

</head>

<body>
<div class="container_16">
    <jsp:include page="static/header.jsp"/>

    <div class="darkmenu">
        <ul class="darkRed" id="eight">
            <li class="current"><a name="#tab1" href="#tab1">Товар</a></li>
            <li><a name="#tab2" href="#tab2">Акции</a></li>
            <li><a name="#tab3" href="#tab3">Пользователи</a></li>
            <li><a name="#tab4" href="#tab4">Правила</a></li>
            <li><a name="#tab5" href="#tab5">Контакты</a></li>
            <li><a name="#tab6" href="#tab6">Что нового</a></li>
            <li><a name="#tab7" href="#tab7">О нас</a></li>
            <li><a name="#tab8" href="#tab8">Смена пароля</a></li>

        </ul>
    </div>
    <div class="clear"></div>

    <div class="grid_16" id="cont">
        <div id="tab1">
            <div class="grid_16 content">
                <div class="grid_8">
                    <table cellpadding="0" cellspacing="0" border="0" class="display" id="lanters">
                        <thead>
                        <tr>
                            <th>Описание</th>
                            <th>Картинка</th>
                            <th>Цена</th>
                            <th>Категория</th>
                            <th>Действие</th>
                        </tr>
                        </thead>

                        <tbody>
                        <c:forEach var="lant" items="${lanterns}">
                        <tr id="lanter_${lant.idLantern}">
                            <td>${lant.description}</td>
                            <td><a href="#" class="dev_img"><img
                                    src="${lant.imgUrl}"
                                    alt="${lant.imgUrl}"
                                    width="60px;"/></a></td>
                            <td>${lant.price}</td>
                            <td>${lant.category.categoryTitle}</td>
                            <td>
                                <a href="javascript:void(0);" onclick="updateLantern('${lant.idLantern}')"
                                   title="Редактировать">
                                    <img src="/img/icons/edit_icon.png" alt="Редактировть"/>
                                </a>
                                &nbsp;
                                <a href="javascript:void(0);" onclick="deleteLantern('${lant.idLantern}')"
                                   title="Удалить">
                                    <img src="/img/icons/delete_icon.png" alt="X"/>
                                </a>
                            </td>
                        </tr>
                        </c:forEach>
                        <tbody>
                    </table>
                </div>

                <div class="grid_8">
                    <div>
                        <form action="/admin/addlantern.html" method="POST" enctype="multipart/form-data" id="add_form">

                            <table>
                                <tr>
                                    <td><label for="description">Описание:&nbsp;</label></td>
                                    <td><input name="description" value=""/></td>

                                </tr>


                                <tr>
                                    <td><label for="document_file">Выберите картинку:&nbsp;</label></td>
                                    <td><input type="file" name="document_file"/></td>

                                </tr>

                                <tr>
                                    <td><label for="price">Цена:&nbsp;</label></td>
                                    <td><input name="price" value=""/></td>

                                </tr>

                                <tr>
                                    <td><label>Категория:&nbsp;</label></td>
                                    <td><select name="lanter_cat" id="add_cat"
                                                style="width:221px !important;">
                                        <option value="">---Выберите категорию---</option>

                                        <c:forEach var="cat" items="${category}">
                                            <option value="${cat.idCategory}">${cat.categoryTitle}</option>
                                        </c:forEach>
                                    </select></td>

                                </tr>

                            </table>

                            <div class="center_button">
                                <button style="margin-left: 20px;" type=" submit" class="button_add">Готово</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>


        <div id="tab2">
            <jsp:include page="admin_action.jsp"/>
        </div>
        <div id="tab3">
            <jsp:include page="admin_users.jsp"/>
        </div>
        <div id="tab4">
            <jsp:include page="admin_rules.jsp"/>
        </div>
        <div id="tab5">
            <jsp:include page="admin_contacts.jsp"/>
        </div>
        <div id="tab6">
            <jsp:include page="admin_news.jsp"/>
        </div>
        <div id="tab7">
            <jsp:include page="admin_about.jsp"/>
        </div>
        <div id="tab8">
            <div class="grid_8">
                <table>

                    <tr><label id="pswd_message" style="color: #cc1426"/></tr>

                    <tr>
                        <td><label for="cur_pswd">Пароль:&nbsp;</label></td>
                        <td><input name="cur_pswd" type="password" value="" id="cur_pswd"/></td>

                    </tr>

                    <tr>
                        <td><label for="new_pswd">Новый пароль:&nbsp;</label></td>
                        <td><input name="new_pswd" type="password" value="" id="new_pswd"/></td>

                    </tr>

                    <tr>
                        <td><label for="new_r_pswd">Повторите новый пароль:&nbsp;</label></td>
                        <td><input name="new_r_pswd" type="password" id="new_r_pswd"/></td>
                    </tr>
                </table>

                <div class="center_button">
                    <button style="margin-left: 20px;" type=" submit" class="button_add" onclick="chechPassword()">
                        Готово
                    </button>
                </div>

            </div>
        </div>
    </div>
</div>


<div id="basic-modal-content">
    <form action="/admin/addlantern.html" method="POST" enctype="multipart/form-data" id="lantern_form">

        <p><label for="description">Описани:&nbsp;</label>
            <input name="description" id="description" value=""/></p>

        <p><label for="document_file">Выберите картинку:&nbsp;</label>
            <input type="file" name="document_file" id="document_file"/>
        </p>

        <p><label for="price">Цена:&nbsp;</label>
            <input name="price" id="price" value=""/></p>

        <select name="lanter_cat" id="cat" style="width:540px !important;">
            <option value="">---Выберите категорию---</option>

            <c:forEach var="cat" items="${category}">
                <option value="${cat.idCategory}">${cat.categoryTitle}</option>
            </c:forEach>
        </select>


        <div class="center_button" id="apply">
            <button type=" submit">Готово</button>
        </div>
    </form>
</div>


</body>
</html>